package com.nl.controller.web.controller;

import com.nl.controller.common.model.Response;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.AdcFunction;
import com.nl.controller.common.util.ResponseUtil;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.bean.Sms_DT;
import com.nl.controller.web.bean.TreeInfo;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.redis.RedisCluster;
import com.nl.controller.web.service.LoginService;
import com.nl.controller.web.util.SendSms;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.JedisCluster;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private CommonService commonService;

    @PostMapping("login")
    public Response login(
            HttpSession session,
            @RequestParam("msisdn") String msisdn,
            @RequestParam("password") String password
    ) {
        SmsUsers user = loginService.login(msisdn, password);
        session.setAttribute("user", user);
        log.info("登录参数：{}", msisdn + " " + password);
        log.debug("登录返回数据：{}", user.toString());
        return ResponseUtil.sucess(user);
    }

    @PostMapping("menu")
    public Response getMenu(
            HttpSession session
    ) {
        SmsUsers user = (SmsUsers) session.getAttribute("user");
        String id = user.getUserId();
        List list = loginService.getMenu(id);
        log.info("获取菜单参数：{}", user.toString());
        log.debug("获取菜单返回值：{}", list.size());
        return ResponseUtil.sucess(list);
    }

    @PostMapping("functions")
    public List<TreeInfo> getFunctions() {
        List list = loginService.getFuncitons();
        log.info("获取权限树：{}");
        log.debug("获取权限树返回值：{}", list.size());
        return list;
    }

    @PostMapping("/login/sendCode")
    public Response sendCode(
            HttpSession session, @RequestParam("msisdn") String msisdn, @RequestParam("password") String password , @RequestParam("flag") String flag
    ) {
    	
    	int result=0;
    	RedisCluster redisCluster=null;
    	try {
    		
    		
    		String number = AdcFunction.getSixNumber(6);
            redisCluster=new RedisCluster(GlobalConst.REDIS_CONFIG);
            //Map<String,String> map =new HashMap<String,String>();
            //组织短信内容
            String smscontent;
            if ("reset".equals(flag)) {
                smscontent = "您好！欢迎使用欢迎名片管理平台，您的密码重置短信验证码是：" + number + "，有效时长为5分钟,请妥善保管，请勿告知他人。";
            } else {
                smscontent = "您好！欢迎登录欢迎名片管理平台，您的短信验证码是：" + number + "，有效时长为5分钟,请妥善保管，请勿告知他人。";
            }
            System.out.println("smscontent = " + smscontent);
            System.out.println("moblie_number = " + msisdn);
            //设置验证码开始获取时间
//            map.put("code", number);
//            map.put("sendTime",String.valueOf(new Long(System.currentTimeMillis())));
//            redisCluster.hmset("yzm"+msisdn, map);
//           redisCluster.expire("yzm"+msisdn, 300);          
//            session.setAttribute("sendTime", new Long(System.currentTimeMillis()));
//            session.setAttribute("number", number);
            
            //验证码信息放入redis中
            redisCluster.set(msisdn+password,number);
            redisCluster.expire(msisdn+password, 300);
            
            Sms_DT dt = SendSms.sendCode(msisdn,smscontent);
            result = loginService.sendCode(dt);
            
            
		} catch (Exception e) {
			log.error("get sendCode failed:"+e.toString());
			e.printStackTrace();
		}finally {
			try {
				redisCluster.close();
			} catch (Exception e2) {
				log.error("close redis error :" + e2.toString());
			}
		}
    	        
        log.info("发送信息参数：{}", msisdn);
        log.debug("发送验证码返回值：{}", result);
        return ResponseUtil.sucess(result);
    }


    @PostMapping("/login/judgeMentCode")
    public String judgeMentCode(HttpSession session, @RequestParam("code") String code, @RequestParam("msisdn") String msisdn, @RequestParam("password") String password) {
    	RedisCluster redisCluster = null;
    	try {
    		redisCluster=new RedisCluster(GlobalConst.REDIS_CONFIG);
//        	Map<String,String> map=redisCluster.hgetAll("yzm"+msisdn);
//        	String number = map.get("code");
//        	Long sendTime=Long.parseLong(map.get("sendTime"));
//        	long currentTime = System.currentTimeMillis();
            String number=redisCluster.get(msisdn+password);
            log.info("---------"+msisdn+password);
     
            if(null!=number&&""!=number){     		
            	if (code.equals(number.toString())) {
            		return "success";
            	}else {
            		return "fail";
            	}
            }else{
            	return "fail";
            }
        	
		} catch (Exception e) {
			log.error("check sendCode failed:"+e.toString());			
			e.printStackTrace();
			return e.toString();			
		}finally {
			try {
				redisCluster.close();
			} catch (Exception e2) {
				log.error("close redis exception : "+ e2.toString());
			}			
		}   	
    }
}
